package org.jeecg.common.util;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class CloneUtil {

    /**
     * 深度复制对象，该对象必须实现Serializable接口
     * @param sourceObject 数据源对象
     * @return 返回深拷贝对象
     */
    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T cloneObject(T sourceObject) {
        T cloneObject = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(sourceObject);
            oos.close();

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);

            //强制类型转化
            cloneObject = (T)ois.readObject();
            ois.close();
        } catch (Exception e) {
            System.out.println("克隆对象出现异常。");
        }
        return cloneObject;
    }

    /**
     * 深度复制Map
     * @param sourceMap 数据源Map
     * @return 返回深拷贝Map
     */
    @SuppressWarnings("unchecked")
    public static <T extends Serializable,K, V> Map<K, V> cloneMap(Map<K, V> sourceMap) {
        Map<K, V> cloneMap = new HashMap<K, V>();
        for(Map.Entry<K, V> entry : sourceMap.entrySet()) {
            T value = (T)entry.getValue();
            V copiedValue = (V)CloneUtil.cloneObject(value);
            cloneMap.put(entry.getKey(), copiedValue);
        }
        return cloneMap;
    }
}